package com.cj.library.widget.view.loadingview;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.AnimationDrawable;
import android.util.AttributeSet;
import android.view.View;

import com.cj.library.widget.R;

/**
 * Created by peter on 2016/9/21.
 */

public abstract class CJLodingView extends View {

    private static final int DEFAULT_FRAMES = 60;

    protected Paint mPaint;
    protected int frame;
    protected Bitmap mCache;
    protected Canvas mCanvas;
    private float padding;

    public CJLodingView(Context context) {
        this(context, null);
    }

    public CJLodingView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CJLodingView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        init(context, attrs);

    }

    protected void init(Context context, AttributeSet attrs) {
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        TypedArray types = context.obtainStyledAttributes(attrs, R.styleable.CJLodingView);
        padding = types.getDimension(R.styleable.CJLodingView_loading_padding, 0);
        frame = types.getInt(R.styleable.CJLodingView_frame, DEFAULT_FRAMES);
        if (frame > 1000) {
            frame = 1000;
        }
        if (frame < 0) {
            frame = 0;
        }
        types.recycle();
    }

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);
        if (mCache == null) {
            mCache = Bitmap.createBitmap(getMeasuredWidth(), getMeasuredHeight(), Bitmap.Config.ARGB_8888);
            mCache.setHasAlpha(true);
            mCanvas = new Canvas(mCache);
        }
        canvas.drawBitmap(mCache, 0, 0, null);
    }

    private Runnable runnable = new AnimationDrawable() {
        @Override
        public void run() {
            long curr = System.currentTimeMillis();

            animRunnableIml();
            drawIml(mCanvas);
            postInvalidate();

            postDelayed(runnable, 1000 / frame);
        }
    };

    public float getPadding() {
        return padding;
    }

    protected abstract void drawIml(Canvas canvas);

    protected abstract void animRunnableIml();

    public void start() {
        stop();
        post(runnable);
    }

    public void stop() {
        removeCallbacks(runnable);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (mCache != null && !mCache.isRecycled()) {
            mCache.recycle();
            mCache = null;
        }
    }
}
